﻿using System;
using System.Collections.Generic;
using System.Data;
using OestsCommon.Model;
using System.Data.SqlClient;

namespace OestsDataBase
{
	/// <summary>
	/// 考试操作
	/// </summary>
	public static class ExamDAL
	{

		private static ExamData ReadData(DataRow dr)
		{
			ExamData ed = new ExamData();
			ed.StudentId = Int32.Parse(dr["student_id"].ToString());
			ed.PaperId = Int32.Parse(dr["paper_id"].ToString());
			ed.Grade = Int32.Parse(dr["grade"].ToString());
			if (!dr["date"].Equals(DBNull.Value))
			{
				ed.Date = dr["date"].ToString();
			}
			return ed;
		}
		/// <summary>
		/// 获得所有的数据
		/// </summary>
		/// <returns></returns>
		public static List<ExamData> GetData()
		{
			string strSql = "select * from T_Exam";
			DataTable dt = SqlHelper.ExecuteDataTable(strSql);
			if (dt == null) { return null; }
			List<ExamData> list = new List<ExamData>();
			foreach (DataRow dr in dt.Rows)
			{
				list.Add(ReadData(dr));
			}
			return list;
		}


		public static List<ExamData> GetExamDataByStudentId(int stdId)
		{
			string strSql = string.Format("select * from T_Exam Where  student_id ={0}", stdId);
			DataTable dt = SqlHelper.ExecuteDataTable(strSql);
			if (dt == null) return null;
			List<ExamData> list = new List<ExamData>();
			foreach (DataRow dr in dt.Rows)
			{
				list.Add(ReadData(dr));
			}
			return list;

		}

		public static List<ExamData> GetExamDataByPeperId(int peperId)
		{
			string strSql = string.Format("select * from T_Exam Where  paper_id ={0}", peperId);
			DataTable dt = SqlHelper.ExecuteDataTable(strSql);
			if (dt == null) return null;
			List<ExamData> list = new List<ExamData>();
			foreach (DataRow dr in dt.Rows)
			{
				list.Add(ReadData(dr));
			}
			return list;
		}


		public static void Add(ExamData data)
		{
			string strSql1 = string.Format("update T_Exam set grade={0}  where student_id=@student and paper_id = @paperId", data.Grade);
			int n = SqlHelper.ExecuteNonQuery(strSql1, new SqlParameter("@student", data.StudentId), new SqlParameter("@paperId", data.PaperId));
			if (n == 0)
			{
				//表示没有该学生的该试卷数据  添加一条
				string strSql2 = string.Format("insert into T_Exam (student_id, paper_id, grade) values({0},{1},{2})",
				data.StudentId, data.PaperId, data.Grade);
				SqlHelper.ExecuteNonQuery(strSql2);
			}
		}
	}
}
